package controller;

import java.sql.ResultSet;

import misc.Configurations;
import misc.Logger;
import misc.Utility;
import data.DatabaseGateway;
import data.File;

public class PasswordProtectController {
    public File retrieveFile(String hashedcode)
    {
        try
        {
            String query =
                      "SELECT * FROM FILES WHERE HashedCode='"+hashedcode+"'";

            DatabaseGateway gw = new DatabaseGateway();
            gw.openConnection(Configurations.User,Configurations.Password,
                                                Configurations.DatabaseName);
            int numRows=gw.executeCount(query);

            if(numRows<=0)
                return null;

            //Querying
            ResultSet rs = gw.executeQuery(query);

            File new_file = new File();
            rs.next();//Move into first row
            new_file.setFileID(rs.getLong("FileID"));
            new_file.setDeleted(rs.getBoolean("isDeleted"));
            new_file.setProtected(rs.getBoolean("isProtected"));
            new_file.setName(rs.getString("OriginalName"));
            new_file.setSize(rs.getLong("Size"));
            new_file.setHashedCode(rs.getString("HashedCode"));
            gw.closeConnection();

            return new_file;
        }
        catch(Exception e)
        {
            Logger.write(e.getMessage(),Logger.LogType.error);
        }

        return null;
    }

    public boolean validate(String pwd1,String pwd2)
    {
        if(pwd1.equalsIgnoreCase("") || pwd2.equalsIgnoreCase(""))
            return false;

        if(!pwd1.equalsIgnoreCase(pwd2))
            return false;

        return true;
    }

    public boolean addPassword(long fileID,String pwd)
    {
        try
        {
            String query = 
                "UPDATE FILES SET HashedPassword='"+Utility.hashMD5(pwd)+"', "+
                "isProtected=true WHERE FileID='"+fileID+"'";

            DatabaseGateway gw = new DatabaseGateway();
            gw.openConnection(Configurations.User,Configurations.Password,Configurations.DatabaseName);
            int c = gw.executeUpdate(query);

            return c==1;
        }
        catch(Exception e)
        {
            Logger.write(e.getMessage(),Logger.LogType.error);
        }

        return false;
    }
}
